import {usemainStore} from '@/stores/mainStore'
import { router, addRouters } from "./router";
import { getToken } from "./composible/cookie";
import { notify } from '@/composible/notify'
import {startLoading,doneLoading} from '@/composible/utils'
//路由前置守卫
router.beforeEach((to, from, next) => {
    //开启进度条
    startLoading();
    const token = getToken("admin-token");
    //未登录情况下
    if (!token && to.path != '/login')
    {
        notify("error", "请先登录");
        return next({path: "/login"});
    }
    //防止重复登录
    if (token && to.path === '/login')
    {
        notify("error", "请勿重复登录");
        return next({ path: from.path ? from.path : '/' }); 
    }

    //获取用户信息
    const mainStore = usemainStore(); 
    let hasNewRouters = false;
    let hasgetUser = false;
    if (token&&!hasgetUser)
    {
        mainStore.getUser();
        hasgetUser = true;
        //动态添加路由
        hasNewRouters=addRouters(mainStore.menus);
    }
    
    //动态标题
    document.title = to.meta.title?to.meta.title:"找不到该页面";
    //登录到对应的位置
    hasNewRouters?next(to.fullPath):next();
})

//后置守卫
router.beforeEach(() => {
    //关闭进度条
    doneLoading();
})

